package com.sd365.permission.centre.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.stuffer.CommonFieldStuffer;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.annotation.stuffer.MethodTypeEnum;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.constant.EntityConsts;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.common.exception.code.BusinessErrorCode;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.core.mq.ActionType;
import com.sd365.common.util.BeanException;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.MessageMapper;
import com.sd365.permission.centre.entity.Message;
import com.sd365.permission.centre.entity.Tenant;
import com.sd365.permission.centre.pojo.dto.DeleteTenantDTO;
import com.sd365.permission.centre.pojo.dto.MessageDTO;
import com.sd365.permission.centre.pojo.dto.TenantDTO;
import com.sd365.permission.centre.pojo.query.MessageQuery;
import com.sd365.permission.centre.service.MessageService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import com.sd365.permission.centre.service.util.SendMQMessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author WangHaitang
 * @date 2022/07/161613
 **/
@Service
public class MessageServiceImpl extends AbstractBaseDataServiceImpl implements MessageService {

    @Resource
    MessageMapper messageMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private SendMQMessageUtil sendMQMessageUtil;

    private static final String TABLE_NAME = "basic_message";

    @CommonFieldStuffer(methodType = MethodTypeEnum.QUERY)
    @Override
    public List<Message> commonQuery(MessageQuery messageQuery) {
        try {
            List<Message> messages = messageMapper.commonQuery(messageQuery);
            Page page = (Page) messages;
            BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
            System.out.println("service层commonQuery");
            return messages;
        } catch (Exception e) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_MESSAGE_DB_EXCEPTION_CODE, e);
        }
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.ADD)
    @Override
    public Boolean add(MessageDTO messageDTO) {
        Message message = BeanUtil.copy(messageDTO, Message.class);

        // todo 业务逻辑判断

        message.setId(idGenerator.snowflakeId());
        super.baseDataStuff4Add(message);
        if (messageMapper.insert(message) > 0) {
            sendMQMessageUtil.SendMessage(ActionType.INSERT, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, message);
            return true;
        } else {
            return false;
        }
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.DELETE)
    @Override
    public Boolean remove(Long id, Long version) {
        try {
            Example example = new Example(Message.class);
            example.createCriteria().andEqualTo("id", id).andEqualTo("version", version);
            if (messageMapper.deleteByExample(example) > 0) {
                Message message = new Message();
                message.setId(id);
                message.setVersion(version);
                sendMQMessageUtil.SendMessage(ActionType.DELETE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, message);
                return true;
            } else {
                return false;
            }
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_MESSAGE_DB_EXCEPTION_CODE, ex);
        }
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.UPDATE)
    @Override
    public Boolean modify(MessageDTO messageDTO) {
        try {
            Message message = BeanUtil.copy(messageDTO, Message.class);

            Example example = new Example(Message.class);
            example.createCriteria().andEqualTo("id", messageDTO.getId()).andEqualTo("version", messageDTO.getVersion());
            super.baseDataStuff4Updated(message);
            if (messageMapper.updateByExampleSelective(message, example) > 0) {
                sendMQMessageUtil.SendMessage(ActionType.UPDATE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, message);
                return true;
            } else {
                return false;
            }
        } catch (BeanException ex) {
            throw new BusinessException(BusinessErrorCode.SYSTEM_BEAN_COPY_EXCEPTION, ex);
        } catch (Exception ex) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_MESSAGE_DB_EXCEPTION_CODE, ex);
        }
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.DELETE)
    @Override
    public Boolean batchDelete(MessageDTO[] messageDTOS) {
        Assert.notEmpty(messageDTOS, "批量删除参数不可以为空");
        List<Object> currentMessage = new ArrayList<>();
        for (MessageDTO messageDTO : messageDTOS) {
            Example example = new Example(Message.class);
            example.createCriteria().andEqualTo("id", messageDTO.getId()).andEqualTo("version", messageDTO.getVersion());
            int result = messageMapper.deleteByExample(example);
            Assert.isTrue(result > 0, String.format("删除的记录id %d 没有匹配到版本", messageDTO.getId()));
            currentMessage.add(messageDTO);
        }
        sendMQMessageUtil.SendMessage(ActionType.DELETE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, currentMessage);
        return true;
    }

    @CommonFieldStuffer(methodType = MethodTypeEnum.UPDATE)
    @Override
    public Boolean batchUpdate(MessageDTO[] messageDTOS) {
        Assert.notEmpty(messageDTOS, "批量更新参数不可以为空");
        List<Object> currentMessage = new ArrayList<>();
        for (MessageDTO messageDTO : messageDTOS) {
            Assert.isTrue(modify(messageDTO), "没有找到相应id更新记录");
            super.baseDataStuff4Updated(BeanUtil.copy(messageDTO, Message.class));
            currentMessage.add(messageDTO);
        }
        sendMQMessageUtil.SendMessage(ActionType.UPDATE, SendMQMessageUtil.EXCHANGE_NAME, TABLE_NAME, currentMessage);
        return true;
    }
}
